package com.leyou.upload.controller;

import com.leyou.upload.service.UploadService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("upload")
public class UploadController {

    @Autowired
    private UploadService uploadService;

    @PostMapping("image")
    public ResponseEntity<String> uploadImage(@RequestParam("file") MultipartFile file) {
        // 调用业务层代码进行文件上传, 返回文件路径
        String url = uploadService.uploadImage(file);
        if (!StringUtils.isNoneBlank(url)) {
            // url为空, 返回错误的响应码
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();// 400
        }
        // 返回文件路径
        return ResponseEntity.ok(url);
    }

}
